﻿const globalName = {
    invalidClass: "is-invalid",
    idTZ: "login",
    idPassword: "passwd",
    idPassword2: "passwd2",
    idLoginBtn: "loginBtn",
    headerPermission: "headerPermission",
	otpregister: "otpregister",
	idNumber: "login",
	idOtpTarget: "passwd",
};

// const globalJQName = {
    // idTZJQ: "#" + globalName.idTZ,
    // idPasswordJQ: "#" + globalName.idPassword,
    // idLoginBtnJQ: "#" + globalName.idLoginBtn,
    // idPassword2JQ: "#" + globalName.idPassword2
// };

const globalJQName = Object.fromEntries(
  Object.entries(globalName)
    .filter(([key]) => key.startsWith("id"))
    .map(([key, val]) => [key + "JQ", `#${val}`])
);

const globals = {
    step: '',
    submited: false,
    card: false,
    nsmsgid: Math.random().toString(16).substring(2, 12),
    errText: document.getElementsByClassName("alert-i--error")[0],
    nextPage: getCookie("NSC_TASS"),
    tokenRefresh: "xyz",
	otpCount: 0,
	otpMax: 3
};

const Step = {
    FULL_LOGIN: 'full_login',
    LOGIN_VERIFICATION: 'login_verification',
    PERMISSION: 'permission',
	UPDATE_DETAILES: 'updateDetailes',
	OTP: 'otp',
	OTP_ERORR: 'error'
};

let otpAndVerification = false;

initCookie();

function initCookie() {
    const ns_callout = getCookie("NS_Callout");

    if (ns_callout) {
        globals.card = true;
        document.getElementById("dAuthorized").classList.remove("d-none");
    } else {
        var min = 60 * 1000 * 4;
        setTimeout(() => {
            const nsc_tass = getCookie("NSC_TASS");
            if (nsc_tass !== globals.tokenRefresh) {
                window.location = "../../refreshapp";
            }
        }, min);
    }

    document.cookie = "NSC_TASS2=" + globals.nsmsgid + "; path=/";
}

function initScreen(form) {
    if (globals.card) {
        return;
    }

    globals.submited = false;

    $("#divMessage").empty();

    const nsMsgErr = form.querySelector(".CredentialTypenone");
    if (nsMsgErr) {
        nsMsgErr.style.display = "none";
    }
	
	const error = form.querySelector(".error");
	if(error){
		const errText = error.textContent;
		if(errText.toLowerCase().includes("the maximum login attempts")){
			globals.step = Step.OTP_ERORR;
			return;
		}
	}
	
    const tzField = form.querySelector(".CredentialTypeusername");
    const passField = form.querySelector(".CredentialTypepassword");
    const loginBtn = form.querySelector(".forms-authentication-button");
    const updateBtn = form.querySelector("#btnNextDetails");
    const updatedMessBtn = form.querySelector("#btnUpdateDetails");
	const otpField = form.querySelector(".CredentialTypeotpregister");

	if(hasInputInside(otpField, globalName.otpregister)){
		initForOtp(form);
		return;
	}
	
	
    if (tzField && passField && loginBtn) {
        addAttrStepOne(form);
    } else {
        if (passField) {
            addAttrStepTwo(form);
        } else if (loginBtn && !updateBtn && !updatedMessBtn) {
            initForPermission(form);
        } else if (updateBtn) {
            initForUpdateDetails(form, "divUpdateDetails" );
        } else if (updatedMessBtn) {
            initForUpdateDetails(form, "divUpdatedMess");
        } else {
            globals.card = true;
            const header = document.getElementById(globalName.headerPermission);
            if (header) {
                header.remove();
            }
            return;
        }
    }
}

function initForUpdateDetails(form, divName) {

	const mainDiv = document.getElementById("mainDiv");
	if(mainDiv){
		mainDiv.classList.add("d-none");
	}

	const divUpdateDetails = document.getElementById(divName);
	if(divUpdateDetails){
		divUpdateDetails.classList.remove("d-none");
		globals.step = Step.UPDATE_DETAILES;
	}
}

function updateDetailes(btnName){
	const btnUpdate = document.getElementById(btnName);
	if(btnUpdate){
		btnUpdate.click();
	}
}

function hasInputInside(container, inputId){
	return container && container.querySelector(`#${inputId}`) !== null;
}

function initForOtp(form) {

	document.title = "רשות המיסים - הזדהות בשימוש בפלאפון";

    if (globals.card) { return; }

    document.getElementById("dUnauthorized").classList.remove("d-none");
	
	const mainTitle = document.getElementById("main-title");
	if(mainTitle){
		mainTitle.textContent= "כניסה לרישום לשירותים הדיגיטליים";
	}
    globals.step = Step.OTP;
	otpAndVerification = true;
	
    const idNumber  = form.querySelector("#" + globalName.idNumber);
    const otpTarget  = form.querySelector("#" + globalName.idOtpTarget);
    const otpChoiceTarget  = form.querySelector(".CredentialTypeotpregister");
    
     if (idNumber) {
         idNumber.classList.add("form-control", "form-control-sm");
         idNumber.setAttribute("maxlength", 9);
         idNumber.setAttribute("aria-required", "true");
         idNumber.setAttribute("aria-invalid", "false");
         idNumber.setAttribute("aria-describedby", "loginErrorMsg");
         idNumber.setAttribute("inputmode", "numeric");
		 idNumber.addEventListener('input', (e) => { e.target.value = e.target.value.replace(/\D+/g, '');
				if(idNumber.getAttribute("aria-invalid")=== "true"){
					if(validateTZ(false)) idError("");
				}
		}, true);
		
		idNumber.addEventListener('blur', ()=> validateTZ(true));
		//idNumber.onkeyup = () => { validateTZ(); }
	}
	
	$(globalJQName.idNumberJQ).after('<div id="loginErrorMsg" class="mb-3 invalid-feedback d-block" aria-live="polite"></div>');

     if (otpTarget) {
         otpTarget.classList.add("form-control", "form-control-sm");
         otpTarget.setAttribute("maxlength", 10);
	     otpTarget.setAttribute("aria-required", "true");    
		 otpTarget.setAttribute('aria-describedby', 'emailOrPhone-desc');
		 otpTarget.setAttribute("inputmode", "numeric");
		 otpTarget.removeAttribute("autocomplete");
		 otpTarget.addEventListener('input', (e) => { e.target.value = e.target.value.replace(/\D+/g, ''); 
				if(otpTarget.getAttribute("aria-invalid") === "true"){
					//validateEmailOrPhone(otpTarget.value, otpTarget, "emailOrPhone-desc");
					const errorElement = document.getElementById("emailOrPhone-desc");
					clearOtpErr(otpTarget, errorElement);
				}
		 }, true);	 	
	 }	
	
	$(globalJQName.idOtpTargetJQ).after('<div id="emailOrPhone-desc" class="mb-3 invalid-feedback d-block" aria-live="polite"></div>');

	  otpTarget.addEventListener('blur', () => {
         validateEmailOrPhone(otpTarget.value, otpTarget, "emailOrPhone-desc");
      });

		
	 const submitBtn = form.querySelector(".forms-authentication-button");
	 if(submitBtn){	 
		 const button = document.createElement("button");
		 button.textContent = "המשך";
		 button.classList.add("btn", "btn-primary", "w-100", "mb-5", "ms-0");
		 button.onclick = chekOtpForm;
		 
		submitBtn.insertAdjacentElement("afterend", button);
		submitBtn.classList.add("d-none");	
	 }
	 
	 otpTarget.addEventListener("keydown", function(e){
		if(e.key === "Enter")
		{e.preventDefault();
			e.stopImmediatePropagation();
			return chekOtpForm();
		}else
		return false;
	});
	
	
	form.addEventListener("keydown", function(e){
		if(e.key === "Enter")
		{e.preventDefault();
			e.stopImmediatePropagation();
			return chekOtpForm();
		}else
		return false;
	});
	
	  
	 document.getElementById("forgotCode")?.classList.add("d-none");
	 document.getElementById("lblReg")?.classList.add("d-none");
	 document.getElementById("lblOPT").style.display = "none";
	 otpChoiceTarget.style.display = "none";
	 	 
	 const errField = form.querySelector(".CredentialTypenone");

    if (errField) {
        var str = $("div.detail-text.error").text();
        var str2 = "נתונים";
        if (str.indexOf(str2) !== 0) {
            $.get("/msgerr.html?" + globals.nsmsgid, (data) => {				
                if (data)              
		          $("#divMessage").append('<div role="alert" aria-live="polite" class="alert-i alert-i--error bi ms-0 me-0">' + data + '</div>');

            });
        }  
    } else {
        $("#divMessage").empty();
    }
	 
	 
    function validateTZ(e) {
        let tz = idNumber.value.trim();
		
		if(!e){		
			return true;
		}
		
        if (tz === "" && globals.submited) {
            idError("מספר זהות הוא שדה חובה");
            return false;
        }
		
        let error = false;
        if (tz.length > 9 || tz === 0 || isNaN(tz)) { error = true; }
        let tmpTZ = parseInt(tz);
        let digits = [0, 0, 0, 0, 0, 0, 0, 0, 0];
        let oneTwo = [1, 2, 1, 2, 1, 2, 1, 2, 1];
        let result = [0, 0, 0, 0, 0, 0, 0, 0, 0];
        // Start filling array from the end
        let i = 8;
        while (tmpTZ > 0) {
            digits[i] = tmpTZ % 10;
            tmpTZ = parseInt(tmpTZ / 10);
            i--;
        }
        for (let j = 0; j < digits.length; j++) {
            let tmpResult = (digits[j] * oneTwo[j]);
            // If number is greater than 9, add both digits
            if (tmpResult > 9) {
                tmpResult -= 9;
            }
            result[j] = tmpResult;
        }
        let iResult = 0;
        for (var x = 0; x < result.length; x++) {
            iResult = iResult + result[x];
        }

        if ((iResult % 10) !== 0) { error = true; }

        (error) ? idError("מספר זהות שגוי") : idError("");
		return !error;
    }

	function idError(message) {
        let errTxt = document.getElementById("loginErrorMsg");				
        if (message !== "") {
            idNumber.classList.add(globalName.invalidClass);
            idNumber.setAttribute("aria-invalid", "true");          
        }
        else {
            idNumber.classList.remove(globalName.invalidClass);
            idNumber.setAttribute("aria-invalid", "false");
        }
        errTxt.innerText = message;
    }
	
	function validateEmailOrPhone(value, inputElement, idErrorElement) {
	  const errorElement = document.getElementById(idErrorElement);
      const trimmedValue = value.trim();
     // const isEmail = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(trimmedValue);

      if (trimmedValue === '') {		 
		otpErr("מספר נייד הוא שדה חובה", inputElement, errorElement);
        return false;
      }

	  // if (!isEmail && !isIsraeliPhone) {
        // errorElement.textContent = 'יש להזין דוא"ל תקין או מספר נייד תקין';
		// inputElement.classList.add(globalName.invalidClass)
        // inputElement.setAttribute('aria-invalid', 'true');
		// if(ifFocus) inputElement.focus();
        // return false;
      // }
	  
	  const isIsraeliPhone = /^05\d{8}$/.test(trimmedValue);
      if (!isIsraeliPhone) {
        otpErr("מספר נייד שגוי", inputElement, errorElement);
        return false;
      }

      clearOtpErr(inputElement, errorElement);
		
	  const otpChoiceTarget  = document.getElementById("otpregister");  
	  if(otpChoiceTarget){
        // if (isEmail) {
        // otpChoiceTarget.checked = false;
      // } else {
       otpChoiceTarget.checked = true;
      }
	  return true;
	}
	 
	 function otpErr(messageErr,inputElement, errorElement){	
		errorElement.textContent = messageErr;
		inputElement.classList.add(globalName.invalidClass);
		inputElement.setAttribute('aria-invalid', 'true');
	 }
	 
	 function clearOtpErr(inputElement, errorElement){		
		errorElement.textContent = '';
		inputElement.removeAttribute('aria-invalid');
		inputElement.classList.remove(globalName.invalidClass); 
	 }
	 
	 function chekOtpForm(form) {
        globals.submited = true;		 
        const phoneValid =  validateEmailOrPhone(otpTarget.value, otpTarget, "emailOrPhone-desc");
		const idValid =  validateTZ(true);

		if(phoneValid && idValid){
			submitBtn.click();
			return true;
		}
		else{
			!idValid ? idNumber.focus() : otpTarget.focus();
			return false;
		}
    }
}


function addAttrStepOne(form) {
    if (globals.card) { return; }
    document.getElementById("dUnauthorized").classList.remove("d-none");
    globals.step = Step.FULL_LOGIN;
    const tzInput = form[0];
    const password = form[1];

    if (tzInput) {
        tzInput.classList.add("form-control", "form-control-sm");
        tzInput.setAttribute("maxlength", 9);
        tzInput.setAttribute("aria-required", "true");
        tzInput.setAttribute("aria-invalid", "false");
        tzInput.setAttribute("aria-describedby", "IDErrMess");
        tzInput.setAttribute("inputmode", "numeric");  	
    }

    if (password) {
        password.classList.add("form-control", "form-control-sm");
        password.setAttribute("maxlength", 6);
        password.setAttribute("aria-required", "true");
        password.setAttribute("aria-describedby", "passErrMess infoPass");		
    }

	
   //  document.getElementById("divAuthGov").classList.remove("d-none");
    document.getElementById("forgotCode").classList.remove("d-none");
    document.getElementById("lblReg").classList.remove("d-none");
    document.getElementById("lblOPT").style.display = "none";
}

function addAttrStepTwo(form) {
    if (globals.card) { return; }
    globals.step = Step.LOGIN_VERIFICATION;
    document.getElementById("dUnauthorized").classList.remove("d-none");
    document.getElementById("lblReg").classList.add("d-none");
  //  document.getElementById("divAuthGov").classList.add("d-none");
    document.getElementById("forgotCode").classList.add("d-none");
	document.getElementById("lblOPT").style.display = "inline";
 
    const password = form[0];
    if (password) {
        password.classList.add("form-control", "form-control-sm");
        password.setAttribute("maxlength", 6);
        password.setAttribute("aria-required", "true");
        password.setAttribute("aria-describedby", "passErrMess");
    }
}


function cancelAuth() {
    event.preventDefault();
    window.location = "../../nslogout";
}

function initForPermission() {
    if (globals.card) { return; }
    globals.step = Step.PERMISSION;
    document.getElementById("lblOPT").style.display = "none";
    const idTitle = 'title';
    const btnNextAuth = 'btnNextAuth';
    const headerPermission = 'headerPermission';

    const newTitle = `
    <div id="headerPermission" class="d-flex justify-content-center">
        <h1>רק רגע של תשומת לב </h1>
        <div class="align-items-center col-1 d-flex justify-content-center">
            <img class="w-75" aria-hidden="true" src="../../ShaamStylesLib/illustrations-icons/heart.png">
        </div>
    </div>`;
    const title = document.getElementById(idTitle);
    const header = document.getElementById(headerPermission);

    if (header) {
        header.remove();
    }

    const btnNext = document.getElementById("btnNextAuth");

    if (title) {
        $('#' + idTitle).empty();
        if (btnNext) {
            $('#' + idTitle).after(newTitle);
        }
    }

    $('#' + btnNextAuth).before('<button type="button" class="btn btn-secondary" onclick="cancelAuth(event)">ביטול ההרשאה</button>');
    $('#' + btnNextAuth).addClass('btn btn-primary m-3 ps-4 pe-4');

    // const btnCancel = document.getElementById("btnCancelAuth");
    // btnCancel.classList.add("btn", "btn-secondary", "m-3");
    // btnCancel.click = (event) => {  event.preventDefault(); window.location = '../../nslogout'; }
    // btnCancel.href = "../../nslogout";

    const rows = document.querySelectorAll('.CredentialTypenone');
    rows.forEach(row => {
        row.classList.add('mb-5');
    });
}

function editStepOne() {
    if (globals.card) { return; }
	
	document.title = "רשות המיסים - כניסה ללקוחות רשומים";

    $(globalJQName.idPasswordJQ).after('<div class="mb-5 text-center"><a href="../../SrRishum" target="_blank" class="withColor">הרשמה או הפקת קוד קבוע חדש</a></div>');
    $(globalJQName.idPasswordJQ).after('<span id="infoPass" class="h5 mb-5"> *קוד המשתמש שקיבלת בתהליך הרישום </span>');
    $(globalJQName.idTZJQ).after('<div id="IDErrMess" class="mb-5 invalid-feedback d-block" aria-live="polite"></div>');
    $(globalJQName.idPasswordJQ).after('<div id="passErrMess" class="invalid-feedback d-block" aria-live="polite"></div>');

    const form = document.querySelector("form");
    const loginBtn = form.querySelector(".forms-authentication-button");
    loginBtn.classList.add("btn", "btn-primary", "w-100", "mb-5", "ms-0");
	loginBtn.setAttribute("role", "button");
    loginBtn.onclick = chekForm;
	
    const tzField = form.querySelector(".CredentialTypeusername");
    const tzInput = tzField.querySelector("input");
	 tzInput.addEventListener('input', (e) => { 
		e.target.value = e.target.value.replace(/\D+/g, '');
		if(tzInput.getAttribute("aria-invalid")=== "true"){
			if(validateTZ(false)) tzError("");
		}
		}, true);

	tzInput.addEventListener('blur', (e)=> { const valid = validateTZ(true); if(e.target.value!=="" && valid===false){e.target.value = e.target.value.padStart(9, '0')}});
		
    const passField = form.querySelector(".CredentialTypepassword");
    const passInput = passField.querySelector("input");
    const errField = form.querySelector(".CredentialTypenone");

    if (errField) {
        var str = $("div.detail-text.error").text();
        var str2 = "נתונים";
        if (str.indexOf(str2) !== 0) {
            $.get("/msgerr.html?" + globals.nsmsgid, (data) => {
                msgerr = data;
                document.getElementsByClassName('detail-text')[4].innerText = msgerr;
            });
        }
        $("#divMessage").append('<div role="alert" aria-live="polite" class="alert-i alert-i--error bi ms-0 me-0">אחד או יותר מהפרטים הוקלדו בצורה שגויה, יש לתקן ולנסות שוב </div>');
    } else {
        $("#divMessage").empty();
    }

    //tzInput.onkeyup = (e) => { validateTZ(e); }
    passInput.onkeyup = () => { validatePassword(); }
	let validPass = false;
		function validatePassword() {
			let errHe = false;
			if (/[^A-Za-z0-9]/g.test(passInput.value)) {
				passwordError("יש להזין אותיות באנגלית וספרות בלבד");
				errHe = true;
			}

			passInput.value = passInput.value.replace(/[^A-Za-z0-9]/g, '');

			if (passInput.value === "" && globals.submited) {
				errHe = true;
				passwordError("קוד משתמש קבוע הוא שדה חובה");
			} else if (!errHe) {
				passwordError("");
			}

		  validPass = !errHe;
		}

    function validateTZ(e) {
        let tz = tzInput.value.trim();
		
		if(!e){		
			return true;
		}
		
        if (tz === "" && globals.submited) {
            tzError("מספר זהות הוא שדה חובה");
            return false;
        }
		
        let error = false;
        if (tz.length > 9 || tz === 0 || isNaN(tz)) { error = true; }
        let tmpTZ = parseInt(tz);
        let digits = [0, 0, 0, 0, 0, 0, 0, 0, 0];
        let oneTwo = [1, 2, 1, 2, 1, 2, 1, 2, 1];
        let result = [0, 0, 0, 0, 0, 0, 0, 0, 0];
        // Start filling array from the end
        let i = 8;
        while (tmpTZ > 0) {
            digits[i] = tmpTZ % 10;
            tmpTZ = parseInt(tmpTZ / 10);
            i--;
        }
        for (let j = 0; j < digits.length; j++) {
            let tmpResult = (digits[j] * oneTwo[j]);
            // If number is greater than 9, add both digits
            if (tmpResult > 9) {
                tmpResult -= 9;
            }
            result[j] = tmpResult;
        }
        let iResult = 0;
        for (var x = 0; x < result.length; x++) {
            iResult = iResult + result[x];
        }

        if ((iResult % 10) !== 0) { error = true; }

       return (error) ? tzError("מספר זהות שגוי") : tzError("");
    }

    function tzError(message) {
        let errTxt = tzField.querySelector(".invalid-feedback");
		let valid = false;
        if (message !== "") {
            tzInput.classList.add(globalName.invalidClass)
            tzInput.setAttribute("aria-invalid", "true");
			valid = true;
        }
        else {
            tzInput.classList.remove(globalName.invalidClass);
            tzInput.setAttribute("aria-invalid", "false");
        }
        errTxt.innerText = message;
		return valid;
    }

    function passwordError(message) {
        let errTxt = passField.querySelector(".invalid-feedback");
        if (message !== "") {
            passInput.classList.add(globalName.invalidClass);
            if (tzField.querySelector(".invalid-feedback") === null || tzField.querySelector(".invalid-feedback").innerText === "") {
                passInput.focus();
            }
        } else {
            passInput.classList.remove(globalName.invalidClass);
        }
        errTxt.innerText = message;
    }

    function chekOnlyNumbers(event) {
        if (event.keyCode == 13 || event.which == 13) {
            tzError("יש להזין ספרות בלבד");
            return false;
        }

        var key_codes = [0, 8, 13, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57];
        var regex = new RegExp("^[0-9]");
        var regexKeys = new RegExp("^[0,13,46,8]");
        var str = String.fromCharCode(!e.charCode ? e.which : e.charCode);
        if (!(regex.test(str) || ($.inArray(e.which, key_codes) >= 0) || (regexKeys.test(str)))) {
            tzError("יש להזין ספרות בלבד");
            return false;
        }
        return true;
    }

  function chekForm() {
        globals.submited = true;
       // (tzInput.value === "") ?  : validateTZ(true);
       const ok = validateTZ(true);
       if(!ok) {
           tzError("מספר זהות הוא שדה חובה");
           tzInput.focus();
       }
        // (passInput.value === "") ? passwordError("שדה חובה") : validatePassword();
        validatePassword()
    }

}

function editStepTwo() {
    if (globals.card) {
        return;
    }
	
	document.title = "רשות המיסים - כניסה ללקוחות רשומים, קוד אימות חד פעמי"
    let passValid = false;
	
	const otpMode = window.location.hostname.includes("signup");
    const form = document.querySelector("form");
	const passField = form.querySelector(".CredentialTypepassword");
    const passInput = passField.querySelector("input");
	// form.addEventListener("keydown", function(event){
		// if(event.key === "Enter")
		// {			
			// chekForm(event);
		// }
	// });
	
	// form.addEventListener("submit", function(event){
		// event.preventDefault();
	// });
	
    // const loginBtn = form.querySelector(".forms-authentication-button");

    // loginBtn.classList.add("btn", "btn-primary", "w-100", "mt-5");
	// loginBtn.setAttribute("role", "button");
    // loginBtn.addEventListener('click', (event) => {chekForm(event)});
	
    $(globalJQName.idPassword2JQ).after('<span id="passErrInfo" class="info-txt"><i class="me-2 bi bi-clock" aria-hidden="true"></i>קוד האימות תקף ל-3 דקות</span>');
    $(globalJQName.idPassword2JQ).after('<div class="invalid-feedback d-block"></div>');
	
	const submitBtn = form.querySelector(".forms-authentication-button");
	 if(submitBtn){	 
		 const button = document.createElement("button");
		 button.textContent = "המשך";
		 button.classList.add("btn", "btn-primary", "w-100", "mt-5");
		 button.onclick = chekForm;
		 
		submitBtn.insertAdjacentElement("afterend", button);
		submitBtn.classList.add("d-none");	
	 }
	 
	 passInput.addEventListener("keydown", function(e){
		if(e.key === "Enter")
		{e.preventDefault();
		//	e.stopImmediatePropagation();
			return chekForm(e);
		}else
		return false;
	});
	
	
	form.addEventListener("keydown", function(e){
		if(e.key === "Enter")
		{e.preventDefault();
		//	e.stopImmediatePropagation();
			return chekForm(e);
		}else
		return false;
	});

    passInput.setAttribute("aria-describedby", "passErrMess passErrInfo");
    passInput.setAttribute('aria-invalid', 'false');
	passInput.setAttribute('type', 'text');

	if(otpMode){
		passInput.setAttribute("inputmode", "numeric");		
	}	
	
    passInput.addEventListener('input', (e) => { 
		if(passInput.getAttribute("aria-invalid")=== "true"){passwordErrorStepTwo("");}
	}, true);

    const errField = form.querySelector(".CredentialTypenone");

	
    if (errField) {
        var str = $("div.detail-text.error").text();
        var str2 = "נתונים";
        if (str.indexOf(str2) !== 0) {
            $.get("/msgerr.html?" + globals.nsmsgid, (data) => {
            document.getElementsByClassName('detail-text')[4].innerText = globals.nsmsgid;
            passValid = true;
			if (passValid && data !== '') {		
                $("#divMessage").append('<div id="passErrMess" role="alert" aria-live="polite" class="alert-i alert-i--error bi ms-0 me-0">' + data + '</div>');
                passInput.setAttribute('aria-invalid', 'true');
            } else {
                validatePassword();
            }
            });
        }
    } else {
        passInput.setAttribute('aria-invalid', 'false');
        $("#divMessage").empty();
        passValid = false;
    }
	
    // if (errField) {
        // $.get("/msgerr.html?" + globals.nsmsgid, (data) => {
            // document.getElementsByClassName('detail-text')[4].innerText = globals.nsmsgid;
            // passValid = true;
			// if (passValid && data !== '') {		
                // $("#divMessage").append('<div id="passErrMess" role="alert" aria-live="polite" class="alert-i alert-i--error bi ms-0 me-0">' + data + '</div>');
                // passInput.setAttribute('aria-invalid', 'true');
            // } else {
                // validatePassword();
            // }
        // });
    // } else {
        // passInput.setAttribute('aria-invalid', 'false');
        // $("#divMessage").empty();
        // passValid = false;
    // }


    //passInput.onkeyup = () => { validatePassword(); }

	passInput.addEventListener('blur', ()=> validatePassword());
	
    function validatePassword() {
		if(otpMode){		
			validateOtpPassword();
		}else{
			validateLoginPassword();
		}    
    }

	function validateOtpPassword() {
		const alert = document.getElementById('passErrMess');
		if(alert){
			alert.remove();
		}
		
		const value = passInput.value;
		const isSixDigits = /^\d{6}$/.test(value);

		if (!isSixDigits) {
			if (value === "") {
				passwordErrorStepTwo("קוד אימות הוא שדה חובה");
			} else if ((!/^\d+$/.test(value)) || (value.length !== 6) || (globals.submited)) {       
				passwordErrorStepTwo("קוד אימות שגוי");
			}
			passValid = false;		
		} else {
			passwordErrorStepTwo("");
			passValid = true;
		}
	}

	
	function validateLoginPassword(){
		let invalid = passInput.value === "" || passInput.value.length < 4 || /[^A-Za-z0-9]/g.test(passInput.value);
        if (invalid) {
            if (passInput.value === "") {
				passwordErrorStepTwo("קוד אימות הוא שדה חובה");
            }
            else if (/[^A-Za-z0-9]/g.test(passInput.value)) {
                passwordErrorStepTwo("יש להזין אותיות באנגלית וספרות בלבד");
                passInput.value = passInput.value.replace(/[^A-Za-z0-9]/g, '');
            } else if (passInput.value.length < 4) {
                passwordErrorStepTwo("קוד אימות שגוי");
            } else if (globals.submited) {
               passwordErrorStepTwo("קוד אימות שגוי");
            }
            passValid = false;           
        } else if (!invalid) {
            passwordErrorStepTwo("");
            passValid = true;
        }
	}
	
    function passwordErrorStepTwo(message) {
        let errTxt = passField.querySelector(".invalid-feedback");
        if(message !== "") { 
			passInput.classList.add(globalName.invalidClass);
			passInput.setAttribute('aria-invalid', 'true');
		}
		else {
			passInput.classList.remove(globalName.invalidClass);
			passInput.setAttribute('aria-invalid', 'false');
		};
        errTxt.innerText = message;
    }

    function chekForm(e) {
		globals.otpCount ++;
		// if(globals.otpCount > 3){
			// $("#mainDiv").append(`
			    // <div class="text-center mt-4">
					// <img src="../../ShaamStylesLib/illustrations/securing.svg">
					// <div class="large-txt mt-3">נחסמת בשל מספר ניסיונות שלא צלחו.<div> אפשר לנסות מאוחר יותר</div>
					// </div>
				// </div>  
			// `);
	      // const lblOPT = document.getElementById("lblOPT");
		  // if(lblOPT){
			  // lblOPT.classList.add("d-none");
		  // }
			// //$("#divMessage").append('<div role="alert" aria-live="polite" class="alert-i alert-i--error bi ms-0 me-0">חרגת ממספר הניסיונות המותרים. יש לנסות שוב מאוחר יותר</div>');
             // //  passInput.setAttribute('aria-invalid', 'true');
			// return false;
		// }
        globals.submited = true;
		validatePassword();
			if(!passValid) {
				passInput.focus();
				return false;
			}else{
				submitBtn.click();
				return true;
			}
    }
}

function editStepPermissions() {
    if (globals.card) { return; }

    document.getElementById("dUnauthorized").classList.remove("d-none");

    // const lblReg = document.getElementById("lblReg");
    // if (lblReg && !lblReg.classList.contains("d-none")) {
    //     lblReg.classList.add("d-none");
    // }

   //  const forgotCode = document.getElementById("divAuthGov");
   //  if (forgotCode && !forgotCode.classList.contains("d-none")) {
     //    forgotCode.classList.add("d-none");
  //   }

    // const divIn = document.querySelector(".p-size-in");
    // if (divIn)
    //     divIn.classList.remove('text-start');
}

function getCookie(cname) {
    const name = cname + "=";
    const decodedCookie = decodeURIComponent(document.cookie);
    const ca = decodedCookie.split(';');
    for (let i = 0; i < ca.length; i++) {
        let c = ca[i];
        while (c.charAt(0) == ' ') {
            c = c.substring(1);
        }
        if (c.indexOf(name) == 0) {
            return c.substring(name.length, c.length);
        }
    }
    return "";
}

function cancelAuth(event) {
    event.preventDefault();
    window.location = "../../nslogout";
}


function initForm() {
    switch (globals.step) {
		 case Step.UPDATE_DETAILES:
            break;
        case Step.FULL_LOGIN:
            editStepOne()
            break;
        case Step.LOGIN_VERIFICATION:		
            editStepTwo();
            break;
        case Step.PERMISSION:
            editStepPermissions();
            break;
		case Step.OTP:
			const otpTarget  = document.getElementById(globalName.idOtpTarget);
			 if (otpTarget) {      
				otpTarget.removeAttribute("autocomplete");		 	
			}	
            break;
		case Step.OTP_ERORR:
			displayOtpErr();
			break;
        default:
            break;
    }
}

function displayOtpErr(){
	$("#mainDiv").append(`
			    <div class="text-center mt-4">
					<img src="../../ShaamStylesLib/illustrations/securing.svg">
					<div class="large-txt mt-3">נחסמת בשל מספר ניסיונות שלא צלחו.<div> אפשר לנסות מאוחר יותר</div><div> יש לשים לב-החסימה תקפה לרישום/הזדהות</div>
					</div>
				</div>  
			`);
	      const lblOPT = document.getElementById("lblOPT");
		  if(lblOPT){
			  lblOPT.classList.add("d-none");
		  }
}


const reload = () => {
    globals.step = '';
    window.location = globals.nextPage;
}

const goTOStep1 = () => {
    window.location = "../../nsstep1";
    return false;
}


